package com.cltech.controller.sys;

import com.cltech.entity.sys.SysExceptionLog;
import com.cltech.frame.result.ResponseBean;
import com.cltech.frame.utils.JWTUtil;
import com.cltech.service.sys.SysExceptionLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.ErrorProperties;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.boot.autoconfigure.web.servlet.error.AbstractErrorController;
import org.springframework.boot.web.servlet.error.ErrorAttributes;
import org.springframework.context.ApplicationContext;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Collections;
import java.util.Date;
import java.util.Map;

/**
 * Created by Administrator on 2019/3/30.
 */
@Controller
@RequestMapping({"${server.error.path:${error.path:/error}}"})
public class GlobalExceptionController extends AbstractErrorController {
    private final ErrorProperties errorProperties;
    @Autowired
    private SysExceptionLogService sysExceptionLogService;
    @Autowired
    public GlobalExceptionController(ErrorAttributes errorAttributes, ServerProperties serverProperties) {
        super(errorAttributes);
        this.errorProperties = serverProperties.getError();
    }

    @Override
    public String getErrorPath() {
        return errorProperties.getPath();
    }

    @RequestMapping(produces = "text/html")
    public ModelAndView errorHtml(HttpServletRequest request, HttpServletResponse response) {
        HttpStatus status = this.getStatus(request);
        Map<String, Object> model = Collections.unmodifiableMap(this.getErrorAttributes(request, this.isIncludeStackTrace(request, MediaType.TEXT_HTML)));
        response.setStatus(status.value());
        String authorization = request.getHeader("Authorization");
        SysExceptionLog sysExceptionLog = new SysExceptionLog();
        if(null != authorization){
            String userId = JWTUtil.getUserId(authorization);
            sysExceptionLog.setOperator(userId);
        }
        final String servletPath = request.getServletPath();
        sysExceptionLog.setPath(servletPath);
        sysExceptionLog.setMessage(model.get("message").toString());
        sysExceptionLog.setCreateTime(new Date());
        sysExceptionLogService.asyncSave(sysExceptionLog);
        ModelAndView modelAndView = this.resolveErrorView(request, response, status, model);
        return modelAndView != null?modelAndView:new ModelAndView("error", model);
    }

    @RequestMapping
    @ResponseBody
    public ResponseBean error(HttpServletRequest request) {
        Map<String, Object> body = this.getErrorAttributes(request, this.isIncludeStackTrace(request, MediaType.ALL));
        HttpStatus status = this.getStatus(request);
        String authorization = request.getHeader("Authorization");
        SysExceptionLog sysExceptionLog = new SysExceptionLog();
        if(null != authorization){
            String userId = JWTUtil.getUserId(authorization);
            sysExceptionLog.setOperator(userId);
        }
        final String servletPath = request.getServletPath();
        sysExceptionLog.setPath(servletPath);
        sysExceptionLog.setMessage(body.get("message").toString());
        sysExceptionLog.setCreateTime(new Date());
        sysExceptionLogService.asyncSave(sysExceptionLog);
        return ResponseBean.error(status.value(),body.get("message").toString());
    }

    protected boolean isIncludeStackTrace(HttpServletRequest request, MediaType produces) {
        ErrorProperties.IncludeStacktrace include = this.getErrorProperties().getIncludeStacktrace();
        return include == ErrorProperties.IncludeStacktrace.ALWAYS?true:(include == ErrorProperties.IncludeStacktrace.ON_TRACE_PARAM?this.getTraceParameter(request):false);
    }

    protected ErrorProperties getErrorProperties() {
        return this.errorProperties;
    }

}
